package com.lxl.jwt1.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    public static  String getToken(String username, Map<String,Object> map){

        return Jwts.builder().setHeaderParam("typ", "JWT")
                //过期时间  一个小时后此token就失效了
                .setExpiration(new Date(System.currentTimeMillis()+3600000))
                .setSubject(username)
                .setClaims(map)
                .signWith(SignatureAlgorithm.HS256, "lxl-jwt").compact();
    }


    public static Boolean validate(String token ){
        try {
            Jwts.parser().setSigningKey("lxl-jwt").parseClaimsJws(token).getBody();//拿到jwt令牌里的载荷部分
            return true;
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("token已经过期");
        } catch (UnsupportedJwtException e) {
            throw new RuntimeException("不支持的token");
        } catch (MalformedJwtException e) {
            throw new RuntimeException("token令牌格式不对");
        } catch (SignatureException e) {
            throw new RuntimeException("token签名问题");
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("参数不合法-密钥不对");
        }
    }

    public static Claims getUserName(String token){

        Claims username = null;
        try {
            username = Jwts.parser().setSigningKey("lxl-jwt").parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("token已经过期");
        } catch (UnsupportedJwtException e) {
            throw new RuntimeException("不支持的token");
        } catch (MalformedJwtException e) {
            throw new RuntimeException("token令牌格式不对");
        } catch (SignatureException e) {
            throw new RuntimeException("token签名问题");
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("参数不合法-密钥不对");
        }
        return username;
    }
}
